﻿using System.Web.Mvc;
using DevExpress.Web.Mvc;
using GridViewCustomBinding.Model;

namespace GridViewCustomBinding.Controllers {
    public class HomeController: Controller {
        [HttpGet, ActionName(CarControllerAction.Car)]
        public ActionResult Index() {
            return View(CarControllerAction.Car);
        }

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post), ActionName(CarControllerAction.Car_Partial)]
        public PartialViewResult Car_Partial() {
            var viewModel = GridViewExtension.GetViewModel("gvCar");
            if (viewModel == null) {
                viewModel = new GridViewModel();
                viewModel.KeyFieldName = "id";

                viewModel.Pager.PageSize = 20;

                viewModel.Columns.Add("id");
                viewModel.Columns.Add("model");
                viewModel.Columns.Add("brand");
                viewModel.Columns.Add("engine.id");
                viewModel.Columns.Add("engine.brand");
                viewModel.Columns.Add("engine.model");
                viewModel.Columns.Add("engine.horsePower");
            }

            viewModel.ProcessCustomBinding(GridViewCustomBindingHelper.GetDataRowCount, GridViewCustomBindingHelper.GetData);

            return PartialView(CarControllerAction.Car_Partial, viewModel);
        }

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post), ActionName(CarControllerAction.Car_Partial_Paging)]
        public PartialViewResult Car_Partial_Paging(GridViewPagerState pager) {
            var viewModel = GridViewExtension.GetViewModel("gvCar");
            viewModel.Pager.Assign(pager); // pager.PageIndex is always 0 ???!!!
            viewModel.ProcessCustomBinding(GridViewCustomBindingHelper.GetDataRowCount, GridViewCustomBindingHelper.GetData);
            return PartialView(CarControllerAction.Car_Partial, viewModel);
        }
    }

    public class CarControllerAction {
        public const string Car = "Index";
        public const string Car_Partial = "Car_Partial";
        public const string Car_Partial_Paging = "Car_Partial_Paging";
    }
}